<!--
  SysGenTest - 管理页面

  功能描述:
  - 数据查询: 支持多字段条件查询和分页
  - 数据展示: 使用SystemTable自定义表格组件
  - 数据操作: 新增、编辑、删除、批量删除
  - 导入导出: 支持Excel数据导入导出

  数据表: sys_gen_test
  模块: test
  权限前缀: tests:gen:test

  生成时间: 2025-10-28 22:08:55
  作者: 系统
-->
<template>
  <div class="app-container p-6">
    <!-- 页面标题和操作按钮 - 完全匹配原型 -->
    <div class="page-header-section flex flex-col md:flex-row md:items-center md:justify-between mb-6">
      <div class="page-title-area">
        <h1 class="text-2xl font-bold text-text-primary">SysGenTest</h1>
        <p class="text-text-muted mt-2">管理SysGenTest数据，包括查询、新增、编辑、删除和批量操作</p>
      </div>
      <div class="page-actions-area mt-4 md:mt-0">
        <!-- 主要操作按钮 -->
        <button
            @click="handleAdd"
            v-permission="'tests:gen:test:add'"
            class="primary-action-btn bg-primary hover:bg-primary-hover text-white px-6 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-plus mr-2"></i>
          <span>新增SysGenTest</span>
        </button>
      </div>
    </div>

    <!-- 搜索和筛选区域 - 完全匹配原型样式 -->
    <div class="search-form-card bg-panel rounded-lg shadow-card p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">


        <!-- 测试字段1搜索 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">测试字段1</label>
          <div class="relative">
            <input
                type="text"
                v-model="queryParams.test1"
                placeholder="请输入测试字段1"
                class="search-input pl-10 pr-4 py-2 w-full rounded-md border border-border bg-bg-hover focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-muted"></i>
          </div>
        </div>


        <!-- 测试字段2搜索 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">测试字段2</label>
          <div class="relative">
            <input
                type="text"
                v-model="queryParams.test2"
                placeholder="请输入测试字段2"
                class="search-input pl-10 pr-4 py-2 w-full rounded-md border border-border bg-bg-hover focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-muted"></i>
          </div>
        </div>
      </div>

      <!-- 高级搜索和操作按钮 -->
      <div class="mt-4 flex justify-between items-center">
        <button class="text-primary hover:text-primary-hover text-sm transition-colors">
          <i class="fas fa-sliders-h mr-1"></i>
          高级搜索
        </button>

        <!-- 操作按钮组 -->
        <div class="flex space-x-3">
          <button
              @click="resetQuery"
              class="px-4 py-2 border border-border rounded-md text-text-secondary hover:bg-bg-hover transition-colors"
          >
            重置
          </button>
          <button
              @click="handleQuery"
              class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-hover shadow-sm transition-colors"
          >
            搜索
          </button>
        </div>
      </div>
    </div>

    <!-- 批量操作工具栏 -->
    <div v-if="selectedIds.length > 0" class="batch-actions-bar bg-panel rounded-lg shadow-card p-4 mb-4 flex justify-between items-center">
      <div class="flex items-center">
        <span class="text-primary font-medium mr-4">已选择 {{ selectedIds.length }} 项</span>
        <button
            @click="handleBatchDelete"
            v-permission="'tests:gen:test:remove'"
            class="px-4 py-2 bg-danger hover:bg-danger-hover text-white rounded-md transition-colors flex items-center"
        >
          <i class="fas fa-trash mr-2"></i>
          <span>批量删除</span>
        </button>
      </div>
      <button
          @click="clearSelection"
          class="px-3 py-1 border border-border rounded-md text-text-secondary hover:bg-bg-hover transition-colors"
      >
        取消选择
      </button>
    </div>

    <!-- 数据表格区域 - 使用SystemTable自定义组件 -->
    <SystemTable
        ref="tableRef"
        :title="'SysGenTest列表'"
        :data="tableData"
        :total="total"
        v-loading="loading"
        row-key="id"
        @page-change="handlePageChange"
        @selection-change="handleSelectionChange"
        @export="handleExport"
        @import="handleImportClick"
        export-permission="tests:gen:test:export"
        import-permission="tests:gen:test:import"
    >
      <!-- 复选框列 -->
      <el-table-column type="selection" width="55" align="center" />

      <!-- ID列 -->
      <el-table-column prop="id" label="ID" width="80" align="center" show-overflow-tooltip />

      <!-- 业务字段列 -->

      <el-table-column
          prop="remark"
          label="备注信息"
          min-width="120"
          show-overflow-tooltip
      />

      <el-table-column
          prop="test1"
          label="测试字段1"
          min-width="120"
          show-overflow-tooltip
      />

      <el-table-column
          prop="test2"
          label="测试字段2"
          min-width="120"
          show-overflow-tooltip
      />

      <!-- 时间字段列 -->

      <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          show-overflow-tooltip
      />

      <el-table-column
          prop="updateTime"
          label="更新时间"
          width="180"
          show-overflow-tooltip
      />

      <!-- 操作列 -->
      <el-table-column label="操作" fixed="right" align="center" width="150">
        <template #default="{ row }">
          <div class="table-actions flex justify-center gap-2">
            <button
                @click="handleEdit(row)"
                v-permission="'tests:gen:test:edit'"
                class="action-btn edit-btn"
                title="编辑"
            >
              <i class="fas fa-edit"></i>
            </button>
            <button
                @click="handleDelete(row)"
                v-permission="'tests:gen:test:remove'"
                class="action-btn delete-btn"
                title="删除"
            >
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </template>
      </el-table-column>
    </SystemTable>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        :close-on-click-modal="false"
        destroy-on-close
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="dialog-form"
      >




        <el-form-item label="ID" v-if="formData.id">
          <el-input v-model="formData.id" disabled />
        </el-form-item>

        <el-form-item
            label="备注信息"
            prop="remark"
        >
          <el-input
              v-model="formData.remark"
              placeholder="请输入备注信息"
          />
        </el-form-item>


        <el-form-item
            label="测试字段1"
            prop="test1"
        >
          <el-input
              v-model="formData.test1"
              placeholder="请输入测试字段1"
          />
        </el-form-item>

        <el-form-item
            label="测试字段2"
            prop="test2"
        >
          <el-input
              v-model="formData.test2"
              placeholder="请输入测试字段2"
          />
        </el-form-item>


      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 导入对话框 -->
    <el-dialog
        v-model="importDialogVisible"
        title="导入SysGenTest"
        width="500px"
        :close-on-click-modal="false"
    >
      <div class="import-section">
        <el-alert
            title="导入说明"
            type="info"
            :closable="false"
            class="mb-4"
        >
          <ul class="list-disc list-inside text-sm">
            <li>请先下载模板，按照模板格式填写数据</li>
            <li>仅支持.xlsx格式文件，大小不超过10MB</li>
            <li>勾选"更新已存在数据"可覆盖现有数据</li>
          </ul>
        </el-alert>

        <div class="mb-4">
          <el-button @click="handleDownloadTemplate" class="w-full">
            <i class="fas fa-download mr-2"></i>
            下载导入模板
          </el-button>
        </div>

        <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            accept=".xlsx,.xls"
            drag
            class="upload-demo"
        >
          <div class="el-upload__text">
            <i class="fas fa-cloud-upload-alt text-4xl text-primary mb-2"></i>
            <div>将文件拖到此处，或<em>点击上传</em></div>
          </div>
        </el-upload>

        <div class="mt-4">
          <el-checkbox v-model="importOptions.updateSupport">
            更新已存在的数据
          </el-checkbox>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="handleImportConfirm"
              :loading="importLoading"
              :disabled="!importFile"
          >
            开始导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * SysGenTest - 管理页面
 *
 * 功能模块:
 * - 数据查询与展示
 * - 新增、编辑、删除操作
 * - 批量删除
 * - Excel导入导出
 *
 *
 * @author 系统
 * @since 2025-10-28 22:08:55
 */
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import SystemTable from '@/components/SystemTable/index.vue'

// 导入API - 使用统一的API对象和WithUI封装函数
import sysGenTestApi, {
  exportSysGenTestWithUI,
  importSysGenTestWithUI,
  downloadSysGenTestTemplateWithUI
} from '@/api/test/SysGenTest'

// ==================== 数据状态 ====================
const loading = ref(false)
const submitLoading = ref(false)
const tableRef = ref()
const formRef = ref<FormInstance>()
const uploadRef = ref()

// 查询参数
const queryParams = reactive<any>({
  current: 1,
  size: 10
})

// 日期范围（用于时间范围查询）
const dateRange = reactive<Record<string, any>>({})

// 表格数据
const tableData = ref<any[]>([])
const total = ref(0)
const selectedIds = ref<any[]>([])

// ==================== 字典数据 ====================

// ==================== 对话框状态 ====================
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive<any>({})

// 表单验证规则
const formRules = reactive({










})


// 导入对话框
const importDialogVisible = ref(false)
const importLoading = ref(false)
const importFile = ref<File | null>(null)
const importOptions = reactive({
  updateSupport: false
})

// ==================== 数据查询 ====================
const getList = async () => {
  loading.value = true
  try {
    const response = await sysGenTestApi.listSysGenTest(queryParams)
    tableData.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('查询失败')
    console.error('查询SysGenTest失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    if (key !== 'current' && key !== 'size') {
      delete queryParams[key]
    }
  })
  // 清空日期范围
  Object.keys(dateRange).forEach(key => {
    dateRange[key] = null
  })
  queryParams.current = 1
  getList()
}

// 日期范围变化处理
const handleDateRangeChange = (field: string) => {
  if (dateRange[field] && dateRange[field].length === 2) {
    queryParams[`${field}Start`] = dateRange[field][0]
    queryParams[`${field}End`] = dateRange[field][1]
  } else {
    delete queryParams[`${field}Start`]
    delete queryParams[`${field}End`]
  }
}

// 分页变化
const handlePageChange = (page: number, pageSize: number) => {
  queryParams.current = page
  queryParams.size = pageSize
  getList()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 清除选择
const clearSelection = () => {
  tableRef.value?.clearSelection()
  selectedIds.value = []
}

// ==================== 新增编辑 ====================
const handleAdd = () => {
  dialogTitle.value = '新增SysGenTest'
  Object.keys(formData).forEach(key => delete formData[key])
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑SysGenTest'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    try {
      if (formData.id) {
        await sysGenTestApi.updateSysGenTest(formData.id, formData)
        ElMessage.success('更新成功')
      } else {
        await sysGenTestApi.createSysGenTest(formData)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}


// ==================== 删除操作 ====================
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除"${row.name || row.id}"吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await sysGenTestApi.deleteSysGenTest(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedIds.value.length} 条数据吗？`,
        '批量删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await sysGenTestApi.batchDeleteSysGenTest(selectedIds.value)
    ElMessage.success(`成功删除 ${selectedIds.value.length} 条数据`)
    clearSelection()
    getList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// ==================== 导入导出 ====================
const handleExport = async () => {
  await exportSysGenTestWithUI(queryParams)
}

const handleImportClick = () => {
  importFile.value = null
  importOptions.updateSupport = false
  importDialogVisible.value = true
}

const handleDownloadTemplate = async () => {
  await downloadSysGenTestTemplateWithUI()
}

const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

const handleImportConfirm = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  importLoading.value = true
  try {
    await importSysGenTestWithUI(
        importFile.value,
        importOptions.updateSupport,
        () => {
          importDialogVisible.value = false
          getList()
        }
    )
  } finally {
    importLoading.value = false
  }
}

// ==================== 辅助函数 ====================

// ==================== 生命周期 ====================
onMounted(() => {
  getList()
  // TODO: 加载字典数据
})
</script>

<style lang="scss" scoped>
// 组件特定样式 - 继承全局样式，只定义特殊样式

.search-form-card {
  .search-input,
  .search-select {
    transition: all 0.3s ease;

    &:focus {
      box-shadow: 0 0 0 2px rgba(var(--primary-rgb), 0.2);
    }
  }
}

.table-actions {
  .action-btn {
    width: 32px;
    height: 32px;
    border-radius: 6px;
    border: 1px solid var(--border);
    background: var(--bg-panel);
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: var(--bg-hover);
      color: var(--text-primary);
    }

    &.edit-btn:hover {
      background: rgba(var(--primary-rgb), 0.1);
      color: var(--primary);
      border-color: var(--primary);
    }

    &.delete-btn:hover {
      background: rgba(var(--danger-rgb), 0.1);
      color: var(--danger);
      border-color: var(--danger);
    }

    &.view-btn:hover {
      background: rgba(var(--success-rgb), 0.1);
      color: var(--success);
      border-color: var(--success);
    }
  }
}

.dialog-form {
  :deep(.el-form-item) {
    margin-bottom: 22px;
  }
}

.import-section {
  :deep(.el-upload) {
    width: 100%;
  }

  :deep(.el-upload-dragger) {
    width: 100%;
  }
}
</style>
